package com.taxi.service;

import com.taxi.constant.IdentityConstant;
import com.taxi.constant.OrderConstants;
import com.taxi.dto.Car;
import com.taxi.dto.OrderInfo;
import com.taxi.remote.ServiceDriverUserClient;
import com.taxi.remote.ServiceMapClient;
import com.taxi.remote.ServiceOrderInfoClient;
import com.taxi.remote.ServiceSsePushClient;
import com.taxi.request.ApiDriverPointRequest;
import com.taxi.request.PushRequest;
import com.taxi.response.PointResponse;
import com.taxi.result.Result;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: aniu
 * @Date: 2023/10/2
 * @ClassName: PointService
 * @Description: Write class functionality and purpose here.
 * @Version: 1.0
 */
@Service
public class PointService {
    @Autowired
    private ServiceDriverUserClient serviceDriverUserClient;
    @Autowired
    private ServiceMapClient serviceMapClient;
    @Autowired
    private ServiceOrderInfoClient serviceOrderInfoClient;
    @Autowired
    private ServiceSsePushClient serviceSsePushClient;

    public Result upload(ApiDriverPointRequest apiDriverPointRequest) {
        //通过carid获取car,调用service-driver-user
        Car car = serviceDriverUserClient.getCarById(apiDriverPointRequest.getCarId()).getData();

        //通过car,获取tid,trid
        String tid = car.getTid();
        String trid = car.getTrid();

        //调用地图去上传
        PointResponse pointResponse = new PointResponse();
        pointResponse.setTid(tid);
        pointResponse.setTrid(trid);
        pointResponse.setPoints(apiDriverPointRequest.getPoints());
        serviceMapClient.upload(pointResponse);

        //司机未接单，上传自己的坐标就行，不用通知乘客
        if(apiDriverPointRequest.getOrderId()==null){
            return Result.ok();
        }
        OrderInfo orderInfo = serviceOrderInfoClient.detail(apiDriverPointRequest.getOrderId()).getData();
        // 到达目的地，不用通知乘客坐标了
        if(orderInfo.getOrderStatus() >= OrderConstants.PASSENGER_GETOFF){
            return Result.ok();
        }
        // 通知乘客
        JSONObject passengerContent = new JSONObject();
        passengerContent.put("orderId",orderInfo.getId());
        passengerContent.put("driverId", orderInfo.getDriverId());
        passengerContent.put("orderStatus",orderInfo.getOrderStatus());
        String[] currentLonLat = apiDriverPointRequest.getPoints()[0].getLocation().split(",");
        passengerContent.put("currentLongitude",currentLonLat[0]);
        passengerContent.put("currentLatitude",currentLonLat[1]);

        PushRequest pushRequest = new PushRequest();
        pushRequest.setUserId(orderInfo.getPassengerId());
        pushRequest.setIdentity(IdentityConstant.PASSENGER_IDENTITY);
        pushRequest.setContent(passengerContent.toString());
        serviceSsePushClient.push(pushRequest);
        return Result.ok();
    }
}
